<template>
	<view class="content">
		<view class="head-wrap" :style="{ position: headerPosition, top: headerTop }">
			<!-- 搜索区域 -->
			<view class="search-wrap uni-flex uni-row">
				<view class="flex-item category-wrap" @click="showCategory = true">
					<view class="iconfont iconsort"></view>
					<text>分类</text>
				</view>

				<view class="flex-item input-wrap">
					<input class="uni-input" maxlength="50" v-model="keyword" confirm-type="search" @confirm="search()" placeholder="请输入您要搜索的商品" />
					<text class="iconfont iconIcon_search" @click.stop="search()"></text>
				</view>

				<view class="flex-item list-style" @click="changeListStyle()">
					<view class="iconfont" :class="{ iconapps: listStyle == 'largest', iconlist1: listStyle == '' }"></view>
					<text>列表</text>
				</view>
			</view>

			<!-- 排序 -->
			<view class="sort-wrap">
				<view :class="{ 'ns-text-color': orderType === '' }" @click="sortTabClick('')">综合</view>
				<view :class="{ 'ns-text-color': orderType === 'sales' }" @click="sortTabClick('sales')">销量</view>
				<view class="price-wrap" @click="sortTabClick('price')">
					<text :class="{ 'ns-text-color': orderType === 'price' }">价格</text>
					<view class="iconfont-wrap">
						<view class="iconfont iconiconangledown-copy" :class="{ 'ns-text-color': priceOrder === 'asc' && orderType === 'price' }"></view>
						<view class="iconfont iconiconangledown" :class="{ 'ns-text-color': priceOrder === 'desc' && orderType === 'price' }"></view>
					</view>
				</view>
				<view
					:class="{ 'ns-text-color': orderType === 'screen' }"
					@click="sortTabClick('screen')"
					v-if="categoryId > 0 && (goodsSpec.length > 0 || attrSpec.length > 0 || categoryBrands.length > 0)"
				>
					筛选
				</view>
			</view>
		</view>

		<view class="goods-list" :class="listStyle">
			<view v-for="(item, index) in goodsList" :key="index" class="goods-item" @click="navToDetailPage(item)">
				<view class="image-wrap"><image :src="$util.img(item.pic_cover_mid)" mode="aspectFill"></image></view>
				<view class="goods-info">
					<text class="goods-name">{{ item.goods_name }}</text>
					<text class="price">{{ item.display_price }}</text>
					<view class="other-info">
						<text v-if="item.shipping_fee == 0">免运费</text>
						<text class="sales">{{ item.sales }} 人付款</text>
					</view>
				</view>
			</view>
		</view>

		<uni-load-more :status="loadingType" :content-text="contentText" v-if="goodsList.length > 0 && pageCount > 1"></uni-load-more>
		<view v-if="isEmpty && goodsList.length == 0" class="empty">
			<view class="iconfont iconwenzhangchaxun"></view>
			<view class="ns-text-color-gray">没有找到商品</view>
		</view>

		<!-- 商品分类弹出框 -->
		<uni-drawer :visible="showCategory" mode="right" @close="showCategory = false">
			<scroll-view scroll-y class="category-list-wrap">
				<view>					
					<text class="first" @click="selectedCategory(0)" :class="{ selected: categoryId == 0 }">全部分类</text>
					<view v-for="(item, index) in categoryList" :key="index" class="list-wrap">
						<text class="first" @click="selectedCategory(item.category_id)" :class="{ selected: item.category_id == categoryId }">{{ item.category_name }}</text>
						<view v-for="(second_item, second_index) in item.child_list" :key="second_index">
							<text class="second" @click="selectedCategory(second_item.category_id)" :class="{ selected: second_item.category_id == categoryId }">
								{{ second_item.category_name }}
							</text>
							<view class="third" v-if="second_item.child_list != ''">
								<view v-for="(third_item, third_index) in second_item.child_list" :key="third_index">
									<uni-tag
										:inverted="true"
										:text="third_item.category_name"
										:type="third_item.category_id == categoryId ? 'primary' : 'default'"
										@click="selectedCategory(third_item.category_id)"
									/>
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</uni-drawer>

		<!-- 筛选弹出框 -->
		<uni-drawer :visible="showScreen" mode="right" @close="showScreen = false" class="screen-wrap">
			<view class="title">筛选</view>
			<scroll-view scroll-y>
				<!-- 品牌筛选项 -->
				<view class="item-wrap" v-if="categoryBrands.length > 0">
					<view class="label">
						<text>品牌</text>
						<!-- iconiconangledown -->
						<view class="iconfont iconiconangledown-copy" v-if="categoryBrands.length > 3"></view>
					</view>
					<view class="list">
						<view v-for="(item, index) in categoryBrands" :key="index">
							<uni-tag :inverted="true" :text="item.brand_name" :type="item.brand_id == brandId ? 'primary' : 'default'" @click="brandId = item.brand_id" />
						</view>
					</view>
				</view>

				<!-- 属性筛选项 -->
				<view class="item-wrap" v-if="attrSpec.length > 0">
					<view v-for="(item, index) in attrSpec" :key="index">
						<view class="label">
							<text>{{ item.attr_value_name }}</text>
							<!-- iconiconangledown -->
							<view class="iconfont iconiconangledown-copy" v-if="item.value_items.length > 3"></view>
						</view>
						<view class="list">
							<view v-for="(child, child_index) in item.value_items" :key="child_index">
								<uni-tag
									:inverted="true"
									:text="child"
									:type="isSelectedAttr(item.attr_value_id, item.attr_value_name, child) ? 'primary' : 'default'"
									@click="selectedAttr(item.attr_value_id, item.attr_value_name, child)"
								/>
							</view>
						</view>
					</view>
				</view>

				<!-- 规格筛选项 -->
				<view class="item-wrap" v-if="goodsSpec.length > 0">
					<view v-for="(item, index) in goodsSpec" :key="index">
						<view class="label">
							<text>{{ item.spec_name }}</text>
							<!-- iconiconangledown -->
							<view class="iconfont iconiconangledown-copy" v-if="item.values.length > 3"></view>
						</view>
						<view class="list">
							<view v-for="(child, child_index) in item.values" :key="child_index">
								<uni-tag
									:inverted="true"
									:text="child.spec_value_name"
									:type="isSelectedSpec(child.spec_id, child.spec_value_id) ? 'primary' : 'default'"
									@click="selectedSpec(child.spec_id, child.spec_value_id)"
								/>
							</view>
						</view>
					</view>
				</view>

				<!-- 价格筛选项 -->
				<view class="item-wrap">
					<view class="label"><text>价格区间(元)</text></view>
					<view class="price-wrap">
						<input class="uni-input" type="digit" v-model="minPrice" placeholder="最低价" />
						<text class="ns-text-color-gray">——</text>
						<input class="uni-input" type="digit" v-model="maxPrice" placeholder="最高价" />
					</view>
				</view>
			</scroll-view>
			<view class="footer">
				<button type="default" @click="showScreen = false">取消</button>
				<button type="primary" @click="screenData">确定</button>
			</view>
		</uni-drawer>
	</view>
</template>

<script>
import http from 'common/js/http.js';
import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
import uniDrawer from '@/components/uni-drawer/uni-drawer.vue';
import uniTag from '@/components/uni-tag/uni-tag.vue';
export default {
	components: {
		uniLoadMore,
		uniDrawer,
		uniTag
	},
	data() {
		return {
			listStyle: '',
			headerPosition: 'fixed',
			headerTop: '0px',
			loadingType: 'loading', //加载更多状态
			orderType: '',
			priceOrder: 'desc', //1 价格从低到高 2价格从高到低
			categoryList: [],
			goodsList: [],
			pageIndex: 1,
			pageCount: 0,
			pageSize: 6,
			order: '',
			sort: 'desc',
			showCategory: false,
			showScreen: false,
			categoryBrands: [], //品牌筛选项
			attrSpec: [], //属性筛选项
			goodsSpec: [], //规格筛选项
			keyword: '',
			categoryId: 0,
			brandId: 0,
			attr: {},
			currAttr: [],
			spec: {},
			currSpec: [],
			minPrice: '',
			maxPrice: '',
			contentText: {
				contentdown: '上拉加载更多',
				contentrefresh: '加载中',
				contentnomore: '没有更多了'
			},
			isEmpty: false,
			ident: false, //防止初始化时，触发上拉加载
			couponTypeId: 0
		};
	},

	onLoad(options) {
		// #ifdef H5
		this.headerTop = document.getElementsByTagName('uni-page-head')[0].offsetHeight + 'px';
		// #endif
		this.categoryId = options.category_id || 0;
		this.brandId = options.brand_id || 0;
		this.keyword = options.keyword || '';
		this.loadCategoryList(this.categoryId);
		this.couponTypeId = options.coupon_type_id || "";
		this.loadData();
	},
	onPageScroll(e) {
		//兼容iOS端下拉时顶部漂移
		if (e.scrollTop >= 0) {
			this.headerPosition = 'fixed';
		} else {
			this.headerPosition = 'absolute';
		}
	},
	//下拉刷新
	onPullDownRefresh() {
		this.loadData('refresh');
	},
	//加载更多
	onReachBottom() {
		if (!this.ident) return;
		this.loadData();
	},
	mixins: [http],
	methods: {
		changeListStyle() {
			if (!this.listStyle) this.listStyle = 'largest';
			else this.listStyle = '';
		},
		//加载分类
		loadCategoryList(fid, sid) {
			this.sendRequest({
				url: 'System.Goods.goodsCategoryTree',
				data: {},
				success: res => {
					if (res.data != null) this.categoryList = res.data;
				}
			});
		},
		//加载商品 ，带下拉刷新和上滑加载
		loadData(type = 'add') {
			//没有更多直接返回
			if (type === 'add') {
				if (this.loadingType === 'nomore') {
					return;
				}
				this.loadingType = 'loading';
			} else {
				this.loadingType = 'more';
			}
			if (type === 'refresh') {
				this.loadingType = 'loading';
				this.pageIndex = 1;
				this.goodsList = [];
			}

			var params = {
				page_index: this.pageIndex,
				page_size: this.pageSize,
				category_id: this.categoryId,
				brand_id: this.brandId,
				attr: this.currAttr.join(';'),
				spec: this.currSpec.join(';'),
				order: this.order,
				sort: this.sort,
				min_price: this.minPrice,
				max_price: this.maxPrice,
				keyword: this.keyword,
				coupon_type_id: this.couponTypeId
			};
			this.sendRequest({
				url: 'System.Goods.goodsListByConditions',
				data: params,
				success: res => {
					this.ident = true;
					let data = res.data;
					this.pageCount = data.goods_list.page_count;
					let goodsList = data.goods_list.data;

					this.categoryBrands = [];
					this.goodsSpec = [];
					this.attrSpec = [];

					//品牌筛选
					if (data.category_brands != undefined) {
						this.categoryBrands.push({ brand_id: 0, brand_name: '全部' });
						this.categoryBrands = this.categoryBrands.concat(data.category_brands);
					} else {
						this.categoryBrands = [];
					}

					//属性筛选
					if (data.attr_or_spec != undefined) {
						this.attrSpec = data.attr_or_spec;
						for (let i = 0; i < this.attrSpec.length; i++) {
							let curr = this.attrSpec[i];
							if (curr.type !== 1 && curr.value !== '' && curr.is_search == 1) {
								if (curr.value_items != null) {
									this.attrSpec[i].value_items.unshift('全部');
								}
							} else {
								this.attrSpec.splice(i, 1);
								i = 0;
								continue;
							}
						}
					} else {
						this.attrSpec = [];
					}

					//规格筛选
					if (data.goods_spec_array != undefined) {
						this.goodsSpec = data.goods_spec_array;

						for (let i = 0; i < this.goodsSpec.length; i++) {
							let curr = this.goodsSpec[i];
							if (curr.is_screen == 1 && curr.spec_name !== '') {
								if (curr.values != null) {
									let item = Object.assign({}, this.goodsSpec[i].values[0]);
									item.spec_value_name = '全部';
									item.spec_value_id = -1;
									this.goodsSpec[i].values.unshift(item);
								}
							} else {
								this.goodsSpec.splice(i, 1);
								i = 0;
								continue;
							}
						}
					} else {
						this.goodsSpec = [];
					}

					if (this.pageCount == 0) {
						this.loadingType = 'nomore';
						this.isEmpty = true;
						this.contentText.contentnomore = '';
					} else {
						if (this.pageIndex < this.pageCount) {
							this.loadingType = 'more';
						} else {
							this.loadingType = 'nomore';
							this.contentText.contentnomore = '没有更多了';
						}
						this.isEmpty = false;

						if (goodsList.length > 0) {
							if (type === 'refresh') {
								this.goodsList = goodsList;
							} else {
								this.goodsList = this.goodsList.concat(goodsList);
							}
							this.pageIndex++;
						}
					}

					if (type === 'refresh') {
						uni.stopPullDownRefresh();
					}
				}
			});
		},
		//筛选点击
		sortTabClick(tag) {
			if (tag == 'sales') {
				this.order = 'sales';
				this.sort = 'desc';
			} else if (tag == 'price') {
				this.order = 'price';
				this.sort = 'desc';
			} else if (tag == 'screen') {
				//筛选
				this.showScreen = true;
				return;
			} else {
				this.order = '';
				this.sort = '';
			}

			if (this.orderType === tag && tag !== 'price') {
				return;
			}
			this.orderType = tag;
			if (tag === 'price') {
				this.priceOrder = this.priceOrder === 'asc' ? 'desc' : 'asc';
				this.sort = this.priceOrder;
			} else {
				this.priceOrder = '';
			}

			this.refreshData();
		},
		//商品详情
		navToDetailPage(item) {
			this.$util.redirectTo('/pages/goods/detail/detail', { goods_id: item.goods_id });
		},
		search() {
			this.refreshData();
		},
		selectedCategory(categoryId) {
			this.categoryId = categoryId;
			this.refreshData();
			this.showCategory = false;
		},

		// 选择属性筛选项
		selectedAttr(attr_value_id, attr_value_name, child) {
			let v = attr_value_name + ',' + child + ',' + attr_value_id;
			if (child == '全部') {
				delete this.attr[attr_value_id];
			} else {
				this.attr[attr_value_id] = v;
			}

			this.currAttr = [];
			for (let i in this.attr) this.currAttr.push(this.attr[i]);
		},

		//是否选中属性
		isSelectedAttr(attr_value_id, attr_value_name, child) {
			let v = attr_value_name + ',' + child + ',' + attr_value_id;
			//精准匹配
			if (this.currAttr.indexOf(v) > -1) {
				return true;
			} else if (child == '全部') {
				//检测是否选中全部
				var tag = -1;
				for (let i in this.attr) {
					tag = this.attr[i].indexOf(attr_value_name);
					if (tag > -1) break;
				}

				if (tag == -1) return true;
			}
			return false;
		},

		// 选择规格筛选项
		selectedSpec(spec_id, spec_value_id) {
			let v = spec_id + ':' + spec_value_id;
			if (spec_value_id == -1) {
				delete this.spec[spec_id];
			} else {
				this.spec[spec_id] = spec_value_id;
			}

			this.currSpec = [];
			for (let i in this.spec) this.currSpec.push(i + ':' + this.spec[i]);
		},

		//是否选中规格
		isSelectedSpec(spec_id, spec_value_id) {
			let v = spec_id + ':' + spec_value_id;
			//精准匹配
			if (this.currSpec.indexOf(v) > -1) {
				return true;
			} else if (spec_value_id == -1) {
				//检测是否选中全部
				var tag = -1;
				for (let i in this.spec) {
					if (i == spec_id) {
						tag = 0;
						break;
					}
				}

				if (tag == -1) return true;
			}
			return false;
		},
		//刷新数据
		refreshData() {
			uni.pageScrollTo({
				duration: 300,
				scrollTop: 0
			});

			this.loadData('refresh');
		},
		screenData() {
			if (this.minPrice != '' && this.maxPrice != '') {
				if (this.minPrice == '') {
					this.$util.showToast({
						title: '请输入最低价'
					});
					return;
				}
				if (this.maxPrice == '') {
					this.$util.showToast({
						title: '最输入最高价'
					});
					return;
				}
				if (this.minPrice != '' && this.minPrice > this.maxPrice) {
					this.$util.showToast({
						title: '最低价不能大于最高价'
					});
					return;
				}
				if (this.maxPrice != '' && this.maxPrice < this.minPrice) {
					this.$util.showToast({
						title: '最高价不能小于最低价'
					});
					return;
				}
			}
			this.refreshData();
			this.showScreen = false;
		}
	}
};
</script>

<style lang="scss">

@import '../public/css/list.scss';
</style>
